package zk.tool.handler;

import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zk.tool.Threads;
import zk.tool.ZKClient;
import zk.tool.model.TreeItemData;
import zk.tool.ui.AppController;
import zk.tool.ui.UIManager;
import zk.tool.util.AlertUtil;
import zk.tool.util.TreeCommon;

public class RefreshTreeItemClickHandler extends AbstractTreeContextMenuClickHandler<TreeItemData> {
    private static final Logger log = LoggerFactory.getLogger(RefreshTreeItemClickHandler.class);

    public RefreshTreeItemClickHandler(TreeView<TreeItemData> treeView, ZKClient client) {
        super(treeView, client);
    }

    @Override
    public void handle0(ActionEvent event, TreeItem<TreeItemData> selectedItem) {
        TreeItemData itemData = selectedItem.getValue();
        if (itemData == null) {
            log.warn("refresh children error, item data is null");
            return;
        }

        Threads.TREE_LOAD_THREAD_POOL.execute(() -> {
            try {
                TreeCommon.refreshData(client, selectedItem);
                TreeCommon.refreshChildren(client, selectedItem);
                Platform.runLater(() -> {
                    AppController controller = UIManager.getInstance().getController(AppController.class);
                    controller.setSelectedItemData(selectedItem.getValue());
                });
            } catch (Exception e) {
                log.error("refresh children error: ", e);
                Platform.runLater(() -> {
                    AlertUtil.exception("刷新节点异常", e);
                });
            }
        });

    }
}
